package it.nola.soccer;

import android.app.ListActivity;
import android.content.Intent;
import android.database.Cursor;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.ListView;
import android.widget.SimpleCursorAdapter;

public class SoccerNotes extends ListActivity {
	public static final int ACTIVITY_CREATE=0; // prima attività
	public static final int ACTIVITY_EDIT=1; // seconda attività
	public static final int TEAM_EDIT=2; // terza attività
	public static final int SUBST_EDIT=3; // quarta attività
	public static final int GOAL_EDIT=4; // quinta attività

	private static final int INSERT_ID=Menu.FIRST; // inserimento
	private static final int MAIL_ID=INSERT_ID+1; // invio email
	private static final int DELETE_ID=MAIL_ID+1;// cancellazione
	private static final int UPDATE_ID=DELETE_ID+1;// aggiornamento

	private DbAdapter mDbHelper;

	private void aggiorna() {
		mDbHelper.aggiornamento();
	}

	private void createNote() {
		Intent i=new Intent(this, NoteEdit.class);
		startActivityForResult(i, ACTIVITY_CREATE);
	}

	/**
	 * Recupera i dati dal db e riempe la lista
	 */
	private void fillData() {
		Cursor cronCursor=mDbHelper.fetchAllTitles();
		startManagingCursor(cronCursor);
		// Crea un array con i campi che vogliamo mostrare in lista (solo il
		// titolo)
		String[] from=new String[] { DbAdapter.KEY_TITOLI };

		// and an array of the fields we want to bind those fields to (in this
		// case just text1)
		int[] to=new int[] { R.id.text1 };

		// Now create a simple cursor adapter and set it to display
		SimpleCursorAdapter cAdapter=new SimpleCursorAdapter(this, R.layout.notes_row, cronCursor,
				from, to);
		setListAdapter(cAdapter);
	}

	private String generaCronacaHTML(Long id) {
		String ret=null;
		Cursor c=mDbHelper.fetchAllNotes(id);
		if (c.moveToFirst()) {
			ret="<h1>"+c.getString(c.getColumnIndex(DbConst.cronache.KEY_TEAM1))+" - "
					+c.getString(c.getColumnIndex(DbConst.cronache.KEY_TEAM2))+" "
					+c.getString(c.getColumnIndex(DbConst.cronache.KEY_RESULT))+"</h1>";
			Cursor cTeam=mDbHelper.cercaSquadra(DbConst.HOME_TEAM, id);
			if (cTeam.moveToFirst()) {
				ret+="<b>"+c.getString(c.getColumnIndex(DbConst.cronache.KEY_TEAM1))+"</b>: <ul>";
				do {
					ret+="<li>"+cTeam.getString(cTeam.getColumnIndex(DbConst.players.KEY_NR))+") "
							+cTeam.getString(cTeam.getColumnIndex(DbConst.players.KEY_NAME))
							+"</li>";
				} while (cTeam.move(1));
				ret+="</ul>";
			}
			cTeam=mDbHelper.cercaSquadra(DbConst.FOREIGN_TEAM, id);
			if (cTeam.moveToFirst()) {
				ret+="<b>"+c.getString(c.getColumnIndex(DbConst.cronache.KEY_TEAM2))+"</b>: <ul>";
				do {
					ret+="<li>"+cTeam.getString(cTeam.getColumnIndex(DbConst.players.KEY_NR))+") "
							+cTeam.getString(cTeam.getColumnIndex(DbConst.players.KEY_NAME))
							+"</li>";
				} while (cTeam.move(1));
				ret+="</ul>";
			}
			ret+="<b>"+getString(R.string.referee)+"</b>: "
					+c.getString(c.getColumnIndex(DbConst.cronache.KEY_REFEREE))+"<br>";
			ret+="<b>"+getString(R.string.assistents)+"</b>: "
					+c.getString(c.getColumnIndex(DbConst.cronache.KEY_ASSISTENT1))+", "
					+c.getString(c.getColumnIndex(DbConst.cronache.KEY_ASSISTENT2))+"<br>";
			ret+="<b>"+c.getString(c.getColumnIndex(DbConst.cronache.KEY_PLACE))+"</b> - "
					+c.getString(c.getColumnIndex(DbConst.cronache.KEY_BODY));
		}
		c.close();
		return ret;
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
		super.onActivityResult(requestCode, resultCode, intent);
		fillData();
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		switch (item.getItemId()) {
		case DELETE_ID:
			AdapterContextMenuInfo info=(AdapterContextMenuInfo) item.getMenuInfo();
			mDbHelper.deleteNote(info.id);
			fillData();
			return true;
		case MAIL_ID:
			sendMail(item);
			return true;
		}
		return super.onContextItemSelected(item);
	}

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		mDbHelper=new DbAdapter(this);
		mDbHelper.open();
		fillData();
		registerForContextMenu(getListView());
	}

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
		menu.add(0, MAIL_ID, 0, R.string.menu_mail);
		menu.add(0, DELETE_ID, 1, R.string.menu_delete);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		menu.add(0, INSERT_ID, 0, R.string.menu_insert);
		menu.add(0, UPDATE_ID, 1, "aggiorna");
		return true;
	}

	@Override
	protected void onListItemClick(ListView l, View v, int position, long id) {
		super.onListItemClick(l, v, position, id);
		Intent i=new Intent(this, NoteEdit.class);
		i.putExtra(DbConst.cronache.KEY_ROWID, id);
		startActivityForResult(i, ACTIVITY_EDIT);
	}

	@Override
	public boolean onMenuItemSelected(int featureId, MenuItem item) {
		switch (item.getItemId()) {
		case INSERT_ID:
			createNote();
			return true;
		case UPDATE_ID:
			aggiorna();
			return true;
		}
		return super.onMenuItemSelected(featureId, item);
	}

	private void sendMail(MenuItem item) {
		AdapterContextMenuInfo info=(AdapterContextMenuInfo) item.getMenuInfo();
		Intent emailIntent=new Intent(android.content.Intent.ACTION_SEND);
		emailIntent.setType("text/html");
		emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL,
				new String[] { "webmaster@website.com" });
		emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
				mDbHelper.recuperaTitolo(info.id));
		emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, generaCronacaHTML(info.id));
		startActivity(Intent.createChooser(emailIntent, getString(R.string.email_send)));
	}

}